package com.mindata.blockchain.core.filter;

import com.mindata.blockchain.socket.common.Const;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * User: jasperxgwang
 * Date: 2018-7-17 10:03
 */
@WebFilter(urlPatterns = "/*")
@Slf4j
public class EncodingFilter implements Filter {
    private String charset;

    public EncodingFilter() {
        this.charset = Const.CHARSET;
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
        String paramCharset = config.getInitParameter("charset");
        if ((paramCharset != null) && (paramCharset.length() > 0)) {
            this.charset = paramCharset;
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        String uri = req.getRequestURI();
        if ((uri.endsWith("html")) || (uri.endsWith("htm")) || (uri.endsWith("xml"))) {
            chain.doFilter(request, response);
            return;
        }
        request.setCharacterEncoding(this.charset);
        response.setCharacterEncoding(this.charset);
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
    }
}
